tool
extends EditorScript
class_name _GitUtil_Terminal


class TerminalThread:
	extends Thread
	
	signal executed(result)
	
	var emitted = false
	
	func _run(arguments: Array):
		emitted = false
		var result := {}
		var output = []
		result["error"] = OS.execute(arguments[0], arguments[1], true, output, true)
		result["output"] = output
		emit_signal("executed", result)
		emitted = true
	
	func execute(path: String, arguments: PoolStringArray):
		if start(self, "_run", [path, arguments]) != OK:
			printerr("执行失败")
		


#============================================================
#   自定义
#============================================================

const TIMEOUT = 30.0

func _git(args: Array):
	print("=".repeat(50))
	print("开始执行：", args[0])
	
	# 线程执行功能
	var thread = TerminalThread.new()
	thread.connect("executed", self, "_executed")
	thread.execute("git", args)
	
	# 检测线程是否执行完成间隔时间
	var interval : float = 0.1
	var time = -1
	var scene_tree = get_editor_interface().get_tree()
	while not thread.emitted:
		time += interval
		if time >= TIMEOUT:
			break
		yield(scene_tree.create_timer(interval), "timeout")
	print("[ 执行时间 ]：%0.3f" % time)
	thread.wait_to_finish()
	yield(scene_tree, "idle_frame")


func _executed(result):
	# 输出执行结果
	print(result)


##  拉取
func pull():
	yield(_git(["pull"]), "completed")


##  提交
## @desc  
func commit(desc: String):
	yield(_git(["add", "."]), "completed")
	yield(_git(["commit", "-m", desc]), "completed")

##  推送
func push():
	yield(_git(["push"]), "completed")

##  提交并推送
## @desc  
func commit_and_push(desc: String):
	yield(commit(desc), "completed")
	yield(push(), "completed")

